package com.ruoyi.framework.security.service

import com.ruoyi.common.enums.UserStatus
import com.ruoyi.common.exception.ServiceException
import com.ruoyi.common.utils.*
import com.ruoyi.framework.security.LoginUser
import com.ruoyi.project.system.domain.SysUser
import com.ruoyi.project.system.service.ISysUserService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.stereotype.Service

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
class UserDetailsServiceImpl : UserDetailsService {

    companion object {
        private val log = LoggerFactory.getLogger(UserDetailsServiceImpl::class.java)
    }

    @Autowired
    private val userService: ISysUserService? = null

    @Autowired
    private val passwordService: SysPasswordService? = null

    @Autowired
    private val permissionService: SysPermissionService? = null
    override fun loadUserByUsername(username: String): UserDetails {
        val user = userService!!.selectUserByUserName(username)!!
        when {
            StringUtils.isNull(user) -> {
                log.info("登录用户：{} 不存在.", username)
                throw ServiceException("登录用户：$username 不存在")
            }

            UserStatus.DELETED.code == user.delFlag -> {
                log.info("登录用户：{} 已被删除.", username)
                throw ServiceException("对不起，您的账号：$username 已被删除")
            }

            UserStatus.DISABLE.code == user.status -> {
                log.info("登录用户：{} 已被停用.", username)
                throw ServiceException("对不起，您的账号：$username 已停用")
            }

            else -> {
                passwordService!!.validate(user)
                return createLoginUser(user)
            }
        }
    }

    fun createLoginUser(user: SysUser): UserDetails {
        return LoginUser(user.userId, user.deptId, user, permissionService!!.getMenuPermission(user))
    }

}
